import { View } from '@tarojs/components'
import { AtIcon, AtButton, AtTabs, AtTabsPane, AtBadge } from 'taro-ui'
import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { Router } from 'tarojs-router-next'

import MyItem from './child/MyItem'
import MyConmment from './child/MyConmment'
import MyItemDetail from './child/MyItemDetail'
import MyRecommended from './child/MyRecommended'
import env from '../../store/env.config'
import './index.scss'
import ShoppingList from './child/ShoppingList'

const Detail = () => {
  const [tabsCurrent, setTabsCurrent] = useState(
    Router.getData()?.current as any | 0
  )
  const [recode, setRecode] = useState(Router.getData() as any)
  const [addr, setAddr] = useState({} as any)
  const [userInfo, setUserInfo] = useState({} as any)
  const [userShppingListNum, setUserShppingListNum] = useState(0 as number)
  const [showShoppingList, setShowShoppingList] = useState(false as any)
  useEffect(() => {
    Taro.getStorage({
      key: 'userInfo',
      success: (userData) => {
        setUserInfo(userData.data)
      },
    })
  }, [])

  useEffect(() => {
    getUserShoppingNum()
  }, [userInfo])

  const getUserShoppingNum = () => {
    if (userInfo.id !== undefined && userInfo.id > 0) {
      Taro.request({
        url: `${env.domain}/shopping/list?userId=${userInfo.id}&token=${userInfo['auth']}`,
        success: (res) => {
          if (res.data['code'] === 200) {
            setUserShppingListNum(res.data.data.recode.length)
          }
        },
      })
    }
  }

  const tabList = [
    {
      title: '商品',
      content: <MyItem recode={recode} setAddr={setAddr} addr={addr} />,
    },
    { title: '评价', content: <MyConmment recode={recode} /> },
    { title: '详情', content: <MyItemDetail recode={recode} /> },
    { title: '推荐', content: <MyRecommended recode={recode} /> },
  ]

  const addShooping = () => {
    let addrJsonStr = JSON.stringify(addr)
    if (addrJsonStr === '{}') {
      Taro.chooseAddress({
        success: function (res) {
          setAddr(res)
        },
      })
      return
    }
    Taro.request({
      url: `${env.domain}/shopping/add?token=${userInfo['auth']}`,
      method: 'POST',
      data: {
        userId: userInfo.id,
        goodsId: recode.id,
        num: 1,
        addr: addrJsonStr,
      },
      success: (res) => {
        Taro.showToast({
          title: res.data.message,
          icon: 'success',
          duration: 2000,
        })
        getUserShoppingNum()
      },
    })
  }

  const getGoodsRecode = () => {
    Taro.request({
      url: `${env.domain}/goods/list`,
      data: {
        page: 1,
        pageSize: 1,
        id: recode['id'],
        token: userInfo['auth'],
      },
      success: (res) => {
        if (res.data.code === 200) {
          setRecode(res['data']['data']['recode'][0])
          return
        }
        Taro.showToast({
          title: res.data.message,
          icon: 'error',
          duration: 1000,
        })
      },
    })
  }

  const addOrder = () => {
    let addrJsonStr = JSON.stringify(addr)
    if (addrJsonStr === '{}') {
      Taro.chooseAddress({
        success: function (res) {
          setAddr(res)
        },
      })
      return
    }
    Taro.showModal({
      title: '确认购买？',
      content: '确认购买点击确定按钮，取消购买点击取消按钮',
      success: function (res) {
        if (res.confirm) {
          Taro.request({
            url: `${env.domain}/order/add?token=${userInfo['auth']}`,
            method: 'POST',
            data: {
              userId: userInfo.id,
              goodsId: recode.id,
              goodsNum: 1,
              remark: '',
              addr: addrJsonStr,
            },
            success: (res) => {
              if (res.data.code === 200) {
                Taro.showToast({
                  title: '您已成功购买该商品',
                  icon: 'success',
                  duration: 1000,
                })
                getGoodsRecode()
                return
              }

              Taro.showToast({
                title: res.data.message,
                icon: 'error',
                duration: 1000,
              })
            },
          })
        } else if (res.cancel) {
          Taro.showToast({
            title: '您已取消购买',
            icon: 'error',
            duration: 1000,
          })
        }
      },
    })
  }

  return (
    <View>
      <View>
        <AtTabs
          current={tabsCurrent}
          tabList={tabList}
          onClick={(val) => {
            setTabsCurrent(val)
          }}
        >
          {tabList.map((item, index) => (
            <AtTabsPane key={index} current={tabsCurrent} index={index}>
              <View className='content-box'>{item.content}</View>
            </AtTabsPane>
          ))}
        </AtTabs>
      </View>
      <View className='bottom-box'>
        <View className='at-row at-row__justify--around at-row__align--center bottom-box-content'>
          <View className='at-col '>
            <AtIcon value='sketch' size={20} />
            <View>店铺</View>
          </View>
          <View className='at-col '>
            <AtIcon value='volume-minus' size={20} />
            <View>客服</View>
          </View>
          <View className='at-col '>
            <AtBadge value={userShppingListNum} maxValue={99}>
              <AtIcon
                onClick={() => {
                  setShowShoppingList(true)
                }}
                value='shopping-cart'
                size={20}
              />
              <View>购物车</View>
            </AtBadge>
          </View>
          <View className='at-col'>
            <AtButton type='primary' size='small' onClick={addShooping}>
              加入购物车
            </AtButton>
          </View>
          <View className='at-col left'>
            <AtButton type='primary' size='small' onClick={addOrder}>
              ¥{recode.price}
            </AtButton>
          </View>
        </View>
      </View>
      <ShoppingList
        show={showShoppingList}
        setShowShoppingList={setShowShoppingList}
        userId={userInfo.id}
        userInfo={userInfo}
      />
    </View>
  )
}

export default Detail
